<?php
declare (strict_types = 1);

namespace app\service\logic\backend\system;

use app\service\logic\BaseService;
use think\Model;
use think\facade\Db;
use app\model\communal\RoleModel;
use app\exception\LogicException;
use app\model\communal\AdminModel;
use app\model\communal\RolePermissionsModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;

final class RoleService extends BaseService
{
    protected string $modelClassName = 'RoleModel';

    /**
     * 查找单挑记录(包含角色权限标识)
     *
     * @param $params
     * @return RoleModel|array|mixed|Model
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function getWithPermissions($params)
    {
        return RoleModel::with(['hasManyPermissions'])->findOrFail($params['id']);
    }

    /**
     * 保存权限
     *
     * @param $params
     * @return bool
     */
    public function permits($params)
    {
        $result = true;
        $role = $this->getSimpleDetail($params);
        Db::connect('communal')->transaction(function () use ($role, $params, &$result) {
            // 中间表先删后增
            RolePermissionsModel::where('role_id', $params['id'])->delete();
            // 角色权限创建
            $rolePermissions = $this->_handleRolePermissionsInsert($params);
            $result = $role->hasManyPermissions()->saveAll($rolePermissions);
        });

        return $result;
    }

    /**
     * 删除
     *
     * @param $params
     * @return bool
     * @throws LogicException
     */
    public function batchDelete($params)
    {
        $ids = explode(',', (string)$params['ids']);

        // 角色下是否存在员工
        if (AdminModel::whereIn('role_id', $ids)->findOrEmpty()->isExists()) {
            throw new LogicException(lang('backend.role have admins'));
        }

        return RoleModel::destroy(function ($query) use ($ids) {
            $query->whereIn('id', $ids);
        });
    }

    /**
     * 处理角色权限新增数据
     *
     * @param $params
     * @return array
     */
    private function _handleRolePermissionsInsert($params)
    {
        $roleId = $params['id'];
        $permissions = $params['permission_ids'];
        $permissions = explode(',', $permissions);
        $rolePermissions = [];
        for ($i = 0; $i < count($permissions); $i++) {
            $rolePermissions[] = [
                'role_id' => $roleId,
                'permissions_id' => $permissions[$i],
            ];
        }

        return $rolePermissions;
    }
}
